package com.singzi.leetcode.N400;

import java.util.Stack;

public class T0394 {
    public static void main(String[] args) {
        Solution0394 solution0347 = new Solution0394();
        System.out.println(solution0347.decodeString("2[ab]"));
    }
}
class Solution0394 {
    public String decodeString(String s) {
        StringBuilder ans = new StringBuilder();
        Stack<Integer> numStack = new Stack<>();
        Stack<StringBuilder> stringStack = new Stack<>();
        int num = 0;
        StringBuilder temp = new StringBuilder();
        for (int i = 0;i < s.length();i++){
            if(s.charAt(i) >='0' && s.charAt(i) <='9'){
                if(temp.length() != 0) stringStack.push(temp);
                num = num*10 + s.charAt(i) - '0';
            }else {
                if(num != 0) numStack.push(num);
                if(s.charAt(i) == '[' || s.charAt(i) == ']'){
                    if(temp.length() != 0){
                        stringStack.push(temp);
                        temp = new StringBuilder();
                    }
                    if(s.charAt(i) == ']'){
                        int n = numStack.pop();
                        while(n  > 0){
                            ans.append(temp);
                            n--;
                        }
                    }
                }else {
                    temp.append(s.charAt(i));
                }
                if(stringStack.isEmpty()){
                    ans.append(s.charAt(i));
                }
                num = 0;
            }
        }


        return ans.toString();

    }
}